#!/usr/bin/python3
# -*- coding: utf-8 -*-

from config import DEPLOY_ROOT_PATH
import os
from config.tools import load_yaml, dump_yaml


ansible_hosts_dir_path = "ansible/inventory/hosts/"
ansible_vars_file_path = "ansible/inventory/vars.yaml"


class ConfAnsibleInventory:

    def __init__(self, root_path=DEPLOY_ROOT_PATH):
        self.root_path = root_path
        self.hosts_dir_path = os.path.join(self.root_path, ansible_hosts_dir_path)
        self.vars_file_path = os.path.join(self.root_path, ansible_vars_file_path)

    def write_ansible_hosts(self, host_name, host_ips=None):
        hosts_file_path = os.path.join(self.hosts_dir_path, host_name)
        
        with open(hosts_file_path, "w") as fw:
            # 清空文件
            fw.seek(0)
            fw.truncate()
            for host_ip in host_ips:
                fw.write(host_ip + "\n")

    def write_ansible_hosts_from_dict(self, host_name, host_ips: dict):
        transform_dict = []
        if host_ips:
            for name in host_ips:
                for ip in host_ips[name]:
                    if ip not in transform_dict:
                        transform_dict.append(ip)
        self.write_ansible_hosts(host_name, transform_dict)

    @staticmethod
    def get_vars_map():
        # 返回vars.yml
        return load_yaml(ConfAnsibleInventory().vars_file_path)

    @staticmethod
    def write_vars_map(ansible_vars_map):
        dump_yaml(ConfAnsibleInventory().vars_file_path, ansible_vars_map)


if __name__ == "__main__":
    home_path = os.environ['HOME']
    deploy_root_path = os.path.join(home_path, "AutoDeploy")
    confAnsible = ConfAnsibleInventory(root_path=deploy_root_path)
    confAnsible.write_ansible_hosts("test", ["x.x.x.x", "y.y.y.y"])
